/**
 * Created by Hzz on 2020/4/30.
 * http配置
 */

import axios from 'axios'
import {getCookie} from '@/utils/aqi'
import router from '../../router'

// axios 配置
axios.defaults.timeout = 60 * 1000
axios.defaults.baseURL = '/'

// http request 拦截器
axios.interceptors.request.use(
  config => {
    // 判断是否存在token，是否登录
    if (getCookie('token')) {
      config.headers.Authorization = getCookie('token').split('"')[1]
    }
      config.headers['Content-Type'] = 'application/json'
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
      if (error.response) {
          switch (error.response.status) {
              case 401:
                  // 当前路由路径
                  const currentPath = router.currentRoute.path

                  // 判断是否为客户路径
                  if (currentPath.startsWith('/customer/web')) {
                      // 如果是客户路径，跳转到客户登录页面
                      router.replace({
                          path: '/customer/web/Login'
                      })
                  }
                  // 判断是否为公司路径
                  else if (currentPath.startsWith('/web/cmsview/crm')) {
                      // 如果是公司路径，跳转到公司登录页面
                      router.replace({
                          path: '/web/cmsview/crm/Login'
                      })
                  }
                  break
          }
      }
    return Promise.reject(error.response.data)
  }
)

export default axios
